#include <QMutex>
#include <QDir>
#include <QDateTime>
#include "defectdetectiondialog.h"
#include "ui_defectdetectiondialog.h"
#include "../mainwindow.h"
#include "../parameter/imageinfo.h"

SeatDetection* pSeatDetection = nullptr;


DefectDetectionDialog::DefectDetectionDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::DefectDetectionDialog)
{
    ui->setupUi(this);
    // 设置窗口标志，允许最大化
    setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint | Qt::Window);

    m_pSeatDetection = MainWindow::instance()->GetSeatDetection();

    ImageInfo& camerainfo = m_pSeatDetection->GetImageInfo();

    InitImageViewWidget();

    InitwidgetSeatPicture();

    InitLogger();
}

DefectDetectionDialog::~DefectDetectionDialog()
{
    int nTotal      = MainWindow::instance()->GetSeatDetection()->GetDetectionWindowInfo().GetImageTotal();
    for (int i = 0; i < nTotal; i++) {
        m_ppImageCameraViewWidgets[i]->setParent(MainWindow::instance());
        m_ppImageCameraViewWidgets[i]->setVisible(false);

        m_ppInfoWidgets[i]->setParent(MainWindow::instance());
    }

    delete ui;
}

void DefectDetectionDialog::InitLogger(){
    QString currentPath = QCoreApplication::applicationDirPath();
    currentPath += "/log";

    QDir dir;
    if (!dir.exists(currentPath)) { // 检查目录是否存在
        if (dir.mkdir(currentPath)) { // 创建目录
            qDebug() << "Directory created successfully:" << currentPath;
        } else {
            qDebug() << "Failed to create directory:" << currentPath;
        }
    } else {
        qDebug() << "Directory already exists:" << currentPath;
    }

    QDateTime dateTime= QDateTime::currentDateTime();//获取系统当前的时间
    QString str = dateTime.toString("yyyy年MM月dd日hh时mm分ss秒");//格式化时间
    m_strFileName = QString("%1/%2.txt").arg(currentPath).arg(str);
    m_pLogger = new Logger(this, m_strFileName, ui->plainTextEditLogger);
}

void DefectDetectionDialog::on_receiveMessage(QString msg){
    m_pLogger->write(msg);
}

void DefectDetectionDialog::ClearImageViewWidgetContent(){
    int nTotal      = MainWindow::instance()->GetSeatDetection()->GetDetectionWindowInfo().GetImageTotal();
    for (int i = 0; i < nTotal; i++) {
        // 清除图像内容
        m_ppImageCameraViewWidgets[i]->ClearBackground();
        // 清除结果标识
        m_ppImageCameraViewWidgets[i]->SetImageResult(0);
    }
}

void DefectDetectionDialog::InitwidgetSeatPicture(){
    ui->widgetSeatPicture->SetImage(QImage(":/icon/res/icon/sf.jpg"));
}

void DefectDetectionDialog::InitImageViewWidget(){
    int nRow,nColumn,nTotal;
    nRow        = MainWindow::instance()->GetSeatDetection()->GetDetectionWindowInfo().GetImageRow();
    nColumn     = MainWindow::instance()->GetSeatDetection()->GetDetectionWindowInfo().GetImageCol();
    nTotal      = MainWindow::instance()->GetSeatDetection()->GetDetectionWindowInfo().GetImageTotal();
    QVector<SubImageInfo*>& subImageInfos = MainWindow::instance()->GetSeatDetection()->GetDetectionWindowInfo().GetSeatFaces();

    m_ppImageCameraViewWidgets = MainWindow::instance()->GetImageCameraViewWidgets();
    m_ppInfoWidgets = MainWindow::instance()->GetInfoWidgets();

    QGridLayout *pLayout = (QGridLayout *) ui->groupBoxImage->layout();
    for (int i = 0; i < nTotal; i++) {
        int row = i / nColumn;
        int col = i % nColumn;

        QVBoxLayout* pVBL = new QVBoxLayout();
        QWidget* pWidget = new QWidget(this);
        pWidget->setStyleSheet("QWidget { background-color: #2e4869; }");
        pWidget->setLayout(pVBL);

        m_ppImageCameraViewWidgets[i]->setParent(this);
        m_ppImageCameraViewWidgets[i]->setVisible(true);
        m_ppImageCameraViewWidgets[i]->SetInfo(QString::number(i));

        m_ppInfoWidgets[i]->setParent(this);  //第二次报错，为什么？

        pVBL->addWidget(m_ppImageCameraViewWidgets[i]);
        pVBL->addWidget(m_ppInfoWidgets[i]);

        m_ppInfoWidgets[i]->SetDefectCount(i); //
        m_ppInfoWidgets[i]->SetFace(subImageInfos.at(i)->GetFace());
        m_ppInfoWidgets[i]->SetPosition(i);

        // 为了双击能显示图片详情设的标志位
        m_ppImageCameraViewWidgets[i]->SetHadDetailInformation(true);
        pLayout->addWidget(pWidget,row,col);
    }
}

void DefectDetectionDialog::on_updateSubImage_signal(int index){
    int imageWidth = MainWindow::instance()->GetSeatDetection()->GetImageInfo().GetImageWidth();
    int imageHeight = MainWindow::instance()->GetSeatDetection()->GetImageInfo().GetImageHeight();
    int imageChannel = MainWindow::instance()->GetSeatDetection()->GetImageInfo().GetImageChannel();
    char* pDestBuffer = MainWindow::instance()->GetImageDestBuffer(index);
    QImage image(imageWidth,imageHeight,QImage::Format_BGR888);
    memcpy(image.bits(),pDestBuffer,imageWidth * imageHeight * imageChannel);
    //QImage image_("d:/test/seat/seatface0.bmp");
    m_ppImageCameraViewWidgets[index]->SetImage(image);
    // 测试使用
    if((index % 2) == 0){
        m_ppImageCameraViewWidgets[index]->SetImageResult(1);
    }else{
        m_ppImageCameraViewWidgets[index]->SetImageResult(-1);
    }
}

void DefectDetectionDialog::on_pushButtonExit_clicked()
{
    this->close();
}


void DefectDetectionDialog::on_pushButtonIsolation_clicked()
{

}

void DefectDetectionDialog::on_pushButtonReset_clicked()
{

}

// 运行一个目标任务
void DefectDetectionDialog::on_pushButtonRelease_clicked()
{
    // （1）清除以前的缺陷图像
    ClearImageViewWidgetContent();
    m_pLogger->write("ClearImageViewWidgetContent");
    // （2）清除以前的缺陷结果
    MainWindow::instance()->ClearDetectionResult();
    m_pLogger->write("MainWindow::instance()->ClearDetectionResult()");
    // （3）运行
    pSeatDetection->GetDescription().run();
    m_pLogger->write("MainWindow::instance()->ClearDetectionResult()");
}

